<template>
  <div class="future-weather">
    <div>
      <h3>最后更新时间:{{ updateTime }}</h3>
    </div>
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from 'dayjs'
import { KEY, API_24H } from "../common/constrant";
import { mapState } from "vuex";
export default {
  data() {
    return {
      hourly: [],
      hourWeatherData: {
        fxTime: [],//x数据
        temp: [],//series数据
      },
      updateTime: ""
    }
  },
  // 获取API数据
  computed: {
    // location:function(){
    //   return this.$store.state.location;
    // }
    ...mapState(["location"])
  },
  created() {
  },
  methods: {
    getData() {
      axios
        .get(API_24H, {
          params: {
            location: this.location.id,
            key: KEY,
          },
        })
        .then((res) => {
          console.log(res.data);
          this.hourly = res.data.hourly;
          this.updateTime = dayjs(res.data.updateTime).format("YYYY-MM-DD HH:mm:ss")
          this.hourWeatherData.fxTime = [];
          this.hourWeatherData.temp = [];
          //遍历24小时天气数据，分别取出部分数据
          this.hourly.forEach(element => {
            this.hourWeatherData.fxTime.push(element.fxTime)
            this.hourWeatherData.temp.push(element.temp)
          });
          //最简便的写法，直按在函数参数中对fxTime数组调用map方法进行元素的处理，把map方法的返回值作为函数的参数
          this.initChart(
            this.hourWeatherData.fxTime.map(e => dayjs(e).format("HH")),
            this.hourWeatherData.temp
          );
        });
    },
    // 初始化图表，有两个参数:x坐标的内容和图表值(y坐标)
    initChart(xAxisData, seriesData) {
      //此种方式是通过fs的dom获取网页元素，但是在vue中不能这么使用
      // var chartDom = document.getElementById("main");
      //这是vue中获取网页元素的方式:ref
      var chartDom = this.$refs.chartContainer;
      var mychart = echarts.init(chartDom);
      var option;
      option = {
        xAxis: {
          type: "category",
          data: xAxisData,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: seriesData,
            type: "line",
          },
        ],
      };
      option && mychart.setOption(option);
    },
  },
  mounted() {
    this.getData();
  },
  watch:{
    location:function(){
      this.getData();
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chart-container {
  height: 20rem;
}
</style>
